<template>
  <el-card shadow="never" class="border-0">
    <!-- 搜索 -->
    <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="品名">
            <el-input v-model="searchForm.partName" placeholder="品名" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="部件型号">
            <el-input v-model="searchForm.partTypeId" placeholder="部件型号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="部件序列号">
            <el-input v-model="searchForm.partSn" placeholder="部件序列号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <div class="flex items-center justify-end">
            <el-button type="primary" @click="initTableData(1)">搜索</el-button>
            <el-button @click="resetSearchForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 新增|刷新 -->
    <div class="flex items-center justify-between mb-4">
      <div>
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <!-- <el-button type="primary" size="small" @click="batchCreate">导入</el-button> -->
        <el-button type="primary" size="small" @click="batchDelete">批量删除</el-button>
      </div>

      <el-tooltip effect="dark" content="刷新数据" placement="top">
        <el-button text @click="initTableData">
          <el-icon :size="20">
            <Refresh />
          </el-icon>
        </el-button>
      </el-tooltip>
    </div>

    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed label="产品型号" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.productTypeCode }}
        </template>
      </el-table-column>
      <el-table-column label="品名" align="center" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.partName }}
        </template>
      </el-table-column>

      <el-table-column label="部件序列号" align="center" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.partSn }}
        </template>
      </el-table-column>

      <el-table-column label="型号规格" align="center" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.partTypeId }}
        </template>
      </el-table-column>
      <el-table-column label="物料编码" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.materialCode }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ dateFormatter(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleClick(scope.row)">
            编辑
          </el-button>
          <el-popconfirm title="是否要删除该部件？" confirmButtonText="确认" cancelButtonText="取消"
            @confirm="handleDelete(scope.row.partId)">
            <template #reference>
              <el-button text type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm> </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
        @current-change="initTableData" />
    </div>
    <div style="display: flex; align-items: center"></div>

    <!-- 新增|修改弹窗 -->
    <el-dialog :title="drawerTitle" v-model="formDrawerRef" width="40%" align-center>
      <el-form :model="form" ref="formRef" label-width="120px" :inline="false" :rules="rules">
        <el-form-item label="产品型号" prop="productTypeCode">
          <el-input v-model="form.productTypeCode" placeholder="产品型号" disabled></el-input>
        </el-form-item>
        <el-form-item label="品名" prop="partName">
          <el-input v-model="form.partName" placeholder="品名"></el-input>
        </el-form-item>
        <el-form-item label="部件序列号" prop="partSn">
          <el-input v-model="form.partSn" placeholder="部件序列号"></el-input>
        </el-form-item>
        <el-form-item label="型号规格" prop="partTypeId">
          <el-input v-model="form.partTypeId" placeholder="型号规格"></el-input>
        </el-form-item>
          <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="物料编码"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="备注"></el-input>
        </el-form-item>
        <el-form-item label="部件图片" prop="files">
          <el-upload class="upload-demo" list-type="picture-card" ref="upload" accept=".jpg,.png" action="#" :limit="1"
            :on-change="fileChange" :file-list="form.files" :before-upload="beforeUpload" :on-exceed="handleExceed"
            :on-remove="handleRemove" :http-request="uploadSubmit" :auto-upload="false">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格(单位分)" prop="price">
          <el-input-number v-model="form.price" />
        </el-form-item>
        <el-form-item label="库存" prop="amount">
          <el-input-number v-model="form.amount" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDrawerRef = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>


<script setup>
import { ref, reactive, computed, onMounted, watch, onBeforeUnmount } from "vue";
import { useRoute } from 'vue-router';
import { dateFormatter } from '~/utils/common.js';
import { toast, toastWarn } from "~/composables/util"
import { addProductPart, deleteProductPart, updateProductPart, getProductPartList } from "~/api/productApi";

const route = useRoute(); // 获取路由实例
const loading = ref(false)
//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
//新增按钮弹窗
const formDrawerRef = ref(false);
const formRef = ref(null)
const selectedRows = ref([]);
const editImgChanged = ref(false)

//新增弹窗表单
const form = reactive({
  productTypeId: null,
  productId: null,
  productTypeCode: "",
  partName: "",
  materialCode: "",
  partSn:"",
  partTypeId: "",
  remarks: "",
  files: [],
  price: 0,
  amount: 0,
  files: [],
});
//上传组件
const upload = ref(null)

const productData = JSON.parse(localStorage.getItem('productData'));


// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

//执行表单校验
const rules = {
  partName: [
    { required: true, message: '部件名称不能为空', trigger: 'change' }
  ],

}

// 查询条件
const searchForm = reactive({
  partName: "",
  partTypeId: null,
  partSn: "",
  productId: null,
  page: currentPage.value,
  size: limit.value,
});
// 重置搜索框
const resetSearchForm = () => {
  searchForm.partName = "";
  searchForm.partTypeId = null;
  searchForm.partSn = "";
  searchForm.productId = null;
  initTableData(1);
};

// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.productId = productData?.productId;
  searchForm.page = currentPage.value
  console.log("查询条件", searchForm);
  getProductPartList(searchForm)
    .then(res => {
      if (res) {
        tableData.value = res.records
        total.value = res.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}


// 新增按钮
const handleCreate = () => {
  //修改标记置为0
  editId.value = 0
  resetForm({
    partId: "",
    productTypeCode: "",
    partName: "",
    materialCode: "",
    partSn: "",
    partTypeId: "",
    remarks: "",
    productTypeId: "",
    price: 0,
    amount: 0,
    files: [],
  })
  form.productTypeCode = productData.productTypeCode
  formDrawerRef.value = true;
}

// 文件移除
const handleRemove = (file, fileList) => {
  form.files = [];
}
// 上传前 文件校验
const beforeUpload = (file) => {
  //console.log("==============" + JSON.stringify(file))
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    toastWarn('上传文件大小不能超过 10MB!')
    return false;
  }
  return true
}
// 文件改变
const fileChange = (file, fileList) => {
  form.files = fileList;
  editImgChanged.value = true
}
// 文件超出个数限制
const handleExceed = (file, fileList) => {
  toastWarn('只能选择一个文件');
}

// 
const uploadSubmit = (param) => {
  console.log('upload 组件触发：', param)
  let paramIo = new FormData()// FormData 对象
  form.productId = productData.productId;
  form.productTypeId = productData.productTypeId;
  for (let key in form) {
    if (key != 'files') {
      paramIo.append(key, form[key])
    }
  }
  if(form.files.length > 0){
      let fileObj = param.file// 相当于input里取得的files
      paramIo.append('files', fileObj)

  }
  paramIo.append("partId", editId.value)
  const fun = editId.value ? updateProductPart(editId.value, paramIo) : addProductPart(paramIo)
  fun.then(res => {
    toast(drawerTitle.value + "成功")
    // 修改刷新当前页，新增刷新第一页
    initTableData(editId.value ? false : 1)
    formDrawerRef.value = false; // 关闭弹窗
  }).catch(err => {
    toast("提交失败", err);
  });
}

// 新增弹窗表单提交
const submitForm = () => {
  console.log('click submit :')
  formRef.value.validate((valid) => {
    console.log('表单验证结果：', valid)
    if (!valid) return
    if (editId.value == 0 || editImgChanged.value == true) {
      if(form.files.length == 0){
        uploadSubmit(form);
      }else{
        upload.value.submit();
      }
    } else {
      let paramIo = new FormData()// FormData 对象
      form.productId = productData.productId;
      form.productTypeId = productData.productTypeId;
      for (let key in form) {
        if (key != 'files') {
          paramIo.append(key, form[key])
        }
      }
      paramIo.append("partId", editId.value)
      updateProductPart(editId.value, paramIo)
        .then(res => {
          toast(drawerTitle.value + "成功")
          // 修改刷新当前页，新增刷新第一页
          initTableData(editId.value ? false : 1)
          formDrawerRef.value = false; // 关闭弹窗
        })
    }

  });
}
// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}

// 批量导入按钮
const batchCreate = () => {
  console.log(productData);
}

//多选框选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
}

//表格数据
const tableData = ref([
]);

//编辑
const handleClick = (row) => {
  console.log('edit 部件 row:', row)
  editId.value = row.partId
  resetForm(row)
  //回显图片
  form.files = [{ url: row.pictureList }]
  formDrawerRef.value = true;
}

// 删除
const handleDelete = (id) => {
  loading.value = true
  deleteProductPart(id).then(res => {
    toast("删除成功")
    initTableData()
  })
    .finally(() => {
      loading.value = false
    })
}

const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    toastWarn("请选择要删除的部件");
    return;
  }

  const ids = selectedRows.value.map(row => row.partId);
  console.log(ids);
  loading.value = true;
  deleteProductPart(ids)
    .then(res => {
      toast("删除成功");
      initTableData();
    })
    .catch(err => {
      console.error("删除失败", err);
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  initTableData();
});
// onBeforeUnmount(() => {
//   localStorage.removeItem('productData');
// });


</script>